package org.hdl.anima.handler;
import java.util.HashMap;
import java.util.Map;

import org.hdl.anima.common.IdentityFactory;
import org.hdl.anima.message.IMessage;

import com.google.common.base.Preconditions;

/**
 * 
 * @author qiuhd
 * @since  2014年8月14日
 */
public final class MessageFactory {

	private final Map<Integer,Class<? extends IMessage>> msgMap;
	
	private static MessageFactory instance = null;
	
	private MessageFactory() {
		msgMap = new HashMap<Integer, Class<? extends IMessage>>();
	}
	
	public static MessageFactory getInstance() {
		if (instance == null) {
			synchronized (IdentityFactory.class) {
				if (instance == null) {
					instance = new MessageFactory();
				}
			}
		}
		return instance;
	}
	
	
	public void register(int msgId,Class<? extends IMessage> clazz) {
		synchronized(this) {
			Preconditions.checkArgument(clazz != null, "Failed to register message in message factory,Cause : clazz is null!");
			msgMap.put(msgId, clazz);
		}
	}
	
	
	public IMessage createMessage(int msgId) {
		Class<? extends IMessage> clazz = msgMap.get(msgId);
		
		if (clazz != null) {
			try {
				IMessage message = clazz.newInstance();
				message.setId(msgId);
				return message;
			} catch (Throwable e) {
				throw new IllegalStateException("Failed to instance message id " + msgId +",cause :" + e.getMessage(),e);
			} 
		}else {
			return null;
		}
	}
}

